package org.jeecg.modules.innerApi.leqiApi.util;

import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.innerApi.leqiApi.responseVo.LQApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Base64;

@Component
@Slf4j
public class LQRequestUtil {

    private final static String serverUrl="http://localhost:8168/QDSKD.do";//乐企接口服务地址

    public final static String aesKey="Jv3CfiyA79RzsWlA";//aes密钥
                                      //(Jv3Cf+iyA79RzsWlAy7We5bdHW8dAYbhdXh4gmK1dhQ=)

    @Autowired
    RedisUtil redisUtil;

    public LQApiResponse request(String jsonStr) {

        log.info("乐企接口请求数据：：" + jsonStr);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, aesKey.getBytes());
        byte[] encryptByte = aes.encrypt(jsonStr);
        String base64Data = Base64.getEncoder().encodeToString(encryptByte);

        String result = doPost(serverUrl, base64Data, null);
        if(StringUtils.isEmpty(result)){
            throw new JeecgBootException("调用乐企接口失败！");
        }
        result = aes.decryptStr(Base64.getDecoder().decode(result));
        log.info("乐企接口返回数据：：" + result);
        LQApiResponse lqApiResponse = JSONObject.parseObject(result,LQApiResponse.class);

        return lqApiResponse;
    }

    private String doPost(String url, String json) {
        return doPost(url, json, null);
    }
    private String doPost(String url, String json, Map<String, Object> headerMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            if(headerMap != null) {
                Iterator<String> it = headerMap.keySet().iterator();
                while(it.hasNext()){
                    String key = it.next();
                    String value = String.valueOf(headerMap.get(key));
                    httpPost.setHeader(key,value);
                }
            }

            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            if (response == null) {
                log.info("http请求url{}异常，返回结果null,", url);
                return null;
            }
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
}
